﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using PagedList;
using System.Collections;

namespace AugustaDevelopersGuild.Controllers
{
    public class UsersController : Controller
    {
        private const int PageSize = 5;

        //
        // GET: /User/
        [Authorize(Roles = "Admin")]
        public ActionResult Index(int? page)
        {
            int pageIndex = page ?? 1;

            MembershipUserCollection viewData = Membership.GetAllUsers();

            IQueryable<MembershipUser> users = viewData.OfType<MembershipUser>().AsQueryable<MembershipUser>();

            return View(users.ToPagedList(pageIndex, PageSize));
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Edit(string userName)
        {
            MembershipUser user = Membership.GetUser(userName);

            return View(user);
        }

        [HttpPost, Authorize(Roles = "Admin")]
        public ActionResult Edit(FormCollection details)
        {
            string username = details["Username"];

            MembershipUser currentUser = Membership.GetUser(username);

            if (!String.IsNullOrEmpty(details["Email"]))
            {
                currentUser.Email = details["Email"];
            }

            Membership.UpdateUser(currentUser);

            //Is a list of all the user roles
            ArrayList removeRoleList = new ArrayList(Roles.GetAllRoles());

            //We are requesting the form variables directly from the form
            foreach (string key in details.AllKeys)
            {
                if (key.StartsWith("role."))
                {
                    String userRole = key.Substring(5, key.Length - 5);
                    removeRoleList.Remove(userRole);
                    if (!Roles.IsUserInRole(username, userRole))
                    {
                        Roles.AddUserToRole(username, userRole);
                    }
                }
            }

            foreach (string removeRole in removeRoleList)
            {
                Roles.RemoveUserFromRole(username, removeRole);
            }

            return RedirectToAction("Index", "Users");
        }
    }
}
